#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "modbus-rtu.h"
#include <stdio.h>
#include <qdebug.h>

//extern int errno;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    modbus_t *ctx;
    uint16_t tab_reg[32];


    ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
    if (ctx == NULL) {
        fprintf(stderr, "Unable to create the libmodbus context\n");
        return ;
    }

    modbus_set_response_timeout(ctx, 2, 500000);

    modbus_set_slave(ctx, 1);

    if (modbus_connect(ctx) == -1) {
//        fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return ;
    }

    /* Read 5 registers from the address 0 */
    //int returnKey=modbus_read_registers(ctx, 0x20, 2, tab_reg);
    int returnKey=modbus_read_registers(ctx, 0x20, 1, tab_reg);
    qDebug()<<returnKey;
//    QString tmpStr=modbus_strerror(errno);
//    qDebug()<<tmpStr;
//    printf("Connection failed: %s\n", modbus_strerror(errno));

    modbus_close(ctx);
    modbus_free(ctx);
}

void MainWindow::on_pushButton_2_clicked()
{
    modbus_t *ctx;
    uint16_t tab_reg[32];


    ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
    if (ctx == NULL) {
        fprintf(stderr, "Unable to create the libmodbus context\n");
        return ;
    }

    modbus_set_slave(ctx, 1);

    if (modbus_connect(ctx) == -1) {
//        fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return ;
    }

    uint8_t raw_req[] = { 0x01, 0x03, 0x00,0x20,0x00,0x01};
    int req_length;
    uint8_t rsp[MODBUS_TCP_MAX_ADU_LENGTH];


    req_length = modbus_send_raw_request(ctx, raw_req, 6 * sizeof(uint8_t));
    int returnKey=modbus_receive_confirmation(ctx, rsp);


    modbus_close(ctx);
    modbus_free(ctx);
}
